package main

import (
	"encoding/json"
	"fmt"
	"github.com/gocolly/colly"
	"github.com/gocolly/colly/extensions"
	"strconv"
)

type ResultBean struct {
	TotalCount int `json:"totalCount"`
	PageSize   int `json:"pageSize"`
	PageNo     int `json:"pageNo"`
	TotalPage  int `json:"totalPage"`
	List       []struct {
		Tybm     string `json:"tybm"`
		Qymc     string `json:"qymc"`
		Shtyxydm string `json:"shtyxydm"`
		Zzjgdm   string `json:"zzjgdm"`
		Gszch    string `json:"gszch"`
		Swdjzh   string `json:"swdjzh"`
		HashCode int64  `json:"hashCode"`
	} `json:"list"`
	TotalRows   int  `json:"totalRows"`
	FirstResult int  `json:"firstResult"`
	FirstPage   bool `json:"firstPage"`
	LastPage    bool `json:"lastPage"`
	NextPage    int  `json:"nextPage"`
	PrePage     int  `json:"prePage"`
}

func GetUrl(i int) (url string) {
	//return fmt.Sprintf("https://www.baidu.com?t=%v", strconv.Itoa(i))
	return fmt.Sprintf("http://xyls.lishui.gov.cn/qy.jspx?searchKey=&pageNo=%v&pageSize=10", strconv.Itoa(i))
}

func main() {
	c := colly.NewCollector()

	extensions.RandomUserAgent(c)
	extensions.Referer(c)

	c.OnRequest(func(r *colly.Request) {
		fmt.Println("链接", r.URL)
	})

	c.OnResponse(func(r *colly.Response) {
		resultBean := ResultBean{}
		var err = json.Unmarshal(r.Body, &resultBean)
		if err != nil {
			fmt.Printf("err=%v", err)
		} else {
			fmt.Println(resultBean.TotalCount)
			rList := resultBean.List
			for i := 0; i < len(rList); i++ {
				tempContent := fmt.Sprintf("%v %v", rList[i].Shtyxydm, rList[i].Qymc)
				fmt.Printf("%v \n", tempContent)
			}
		}
	})

	//_proxy := "http://" + GetProxy()
	//fmt.Println("使用代理：", _proxy)
	//c.SetProxy(_proxy)

	c.Visit(GetUrl(1))
}
